package com.bood.shimmer.common.filter;

import com.bood.shimmer.common.api.Result;
import com.bood.shimmer.common.constant.ShimmerConstants;
import com.bood.shimmer.common.enums.ResultEnum;
import com.bood.shimmer.common.utils.StringUtils;
import com.bood.shimmer.shiro.JwtToken;
import com.bood.shimmer.shiro.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * JWT 核心过滤器配置 所有的请求都会先经过 Filter，所以我们继承官方的 BasicHttpAuthenticationFilter，并且重写鉴权的方法。
 * 执行流程 preHandle->isAccessAllowed->isLoginAttempt->executeLogin
 * </p>
 *
 * @author：bood
 * @date：2020/9/23
 */
public class JwtFilter extends BasicHttpAuthenticationFilter {

    /**
     * <p>
     * 判断用户是否想要进行 需要验证的操作
     * 检测 header 里面是否包含 权限令牌（访问）标识 字段即可
     * 调用情况请查看 BasicHttpAuthenticationFilter 源码
     * </p>
     *
     * @param request:
     * @return：java.lang.String
     * @author：bood
     * @date：2020/9/23
     */
    @Override
    protected String getAuthzHeader(ServletRequest request) {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        return httpRequest.getHeader(ShimmerConstants.AUTHORIZATION_TOKEN);
    }

    /**
     * <p>
     * 判断用户是否想要需要验证的操作
     * 检测 header 里面是否包含 权限令牌（访问）标识 字段即可
     * </p>
     *
     * @param request:
     * @param response:
     * @return：boolean
     * @author：bood
     * @date：2020/9/23
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        String auth = getAuthzHeader(request);
        return StringUtils.isNotBlank(auth);
    }

    /**
     * <p>
     * 此方法调用登陆，验证逻辑
     * </p>
     *
     * @param request:
     * @param response:
     * @param mappedValue:
     * @return：boolean
     * @author：bood
     * @date：2020/9/23
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        if (isLoginAttempt(request, response)) {
            JwtToken token = new JwtToken(getAuthzHeader(request));
            try {
                getSubject(request, response).login(token);
                // 封装 JwtToken
                JwtUtil jwtUtil = new JwtUtil();
                token.setId(jwtUtil.getIdByToken(token.getToken()));
                token.setIp(jwtUtil.getIpByToken(token.getToken()));

                httpServletRequest.setAttribute(ShimmerConstants.AUTHORIZATION_TOKEN, token);
            } catch (Exception e) {
                responseError(httpServletResponse, "Token is invalid,please check your token!");
                return false;
            }
        }
        return true;
    }

    /**
     * <p>
     * 提供跨域支持
     * </p>
     *
     * @param request:
     * @param response:
     * @return：boolean
     * @author：bood
     * @date：2020/9/23
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("*"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("*"));
        // 跨域时会首先发送一个 option 请求，这里我们给 option 请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        // 如果不带 权限令牌（访问）标识，去验证 Shiro
        if (!isLoginAttempt(request, response)) {
            responseError(httpServletResponse, "Token is invalid,please check your token!");
            return false;
        }

        return super.preHandle(request, response);
    }

    private void responseError(ServletResponse response, String msg) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(ResultEnum.SIGNATURE_NOT_MATCH.code());
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json;charset=UTF-8");
        try {
            String resJson = new ObjectMapper().writeValueAsString(new Result(ResultEnum.SIGNATURE_NOT_MATCH.code(), msg));
            httpResponse.getWriter().append(resJson);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}